<template>
  <!-- 外层容器：控制整个页面背景 -->
  <div class="page-container">
    <!-- 输入框和录入按钮开始 -->
    <div class="btns">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-form-item>
              <el-button type="primary" @click="toAdd">录入</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 输入框和录入按钮结束 -->
    
    <!-- 表格开始：单独设置背景以区分区域 -->
    <div class="table-container">
      <el-table :data="engData" border style="width: 100%" class="custom-table">
        <el-table-column type="index" :index="1" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="serial_number" label="编号" width="180" align="center"></el-table-column>
        <el-table-column prop="name" label="名称" width="360" align="center"></el-table-column>
        <el-table-column prop="type" label="工程类型" align="center">
          <template v-slot="scope">
            <div>
              <el-tag v-if="scope.row.type == '事业单位'">事业单位</el-tag>
              <el-tag v-else-if="scope.row.type == '写字楼'" type="warning">写字楼</el-tag>
              <el-tag v-else-if="scope.row.type == '园区'" type="danger">园区</el-tag>
              <el-tag v-else type="success">建筑工地</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="开始时间" align="center">
          <template v-slot="scope">
            <div>{{ scope.row.create_time | fmtDate }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" align="center">
          <template v-slot="scope">
            <div>{{ scope.row.end_time == null ? "未结束" : moment(scope.row.end_time).format('YYYY-MM-DD:HH:mm:ss') }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template v-slot="scope">
            <div>
              <el-tag v-if="scope.row.status == '监测中'" effect="dark" type="success">监测中</el-tag>
              <el-tag v-else-if="scope.row.status == '未绑定'" effect="dark" type="warning">未绑定</el-tag>
              <el-tag v-else effect="dark" type="danger">已结束</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <div>
              <el-link @click="toEdit(scope.row)" :underline="false" type="success">修改</el-link>
              <el-link @click="toBind(scope.row)" :disabled="scope.row.status == '已结束'" :underline="false" type="primary">绑定</el-link>
              <el-link @click="toFinish(scope.row.id)" :disabled="scope.row.status == '已结束' || scope.row.status == '未绑定'" :underline="false" type="danger">结束</el-link>
              <el-link @click="toDelete(scope.row.id)" :disabled="scope.row.status == '已结束' || scope.row.status == '监测中'" :underline="false" type="warning">删除</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 表格结束 -->
    
    <!-- 分页开始 -->
    <div class="page" style="margin-top: 10px;">
      <el-pagination hide-on-single-page @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="params.page" :page-sizes="[5, 8, 10, 20]" :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 分页结束 -->
    
    <!-- 抽屉：设置粉紫色背景 -->
    <el-drawer @close="reset" size="60%" :title="title" :visible.sync="visible" direction="rtl" custom-class="demo-drawer custom-drawer"
      ref="drawer">
      <div class="demo-drawer__content" style="padding-right: 10px;">
        <el-form :rules="rules" ref="myForm" :model="formSave">
          <!-- 原有表单内容不变 -->
          <el-row>
            <el-col :span="12">
              <el-form-item prop="serial_number" label="工程编号" :label-width="formLabelWidth">
                <el-input class="input" clearable placeholder="请输入工程编号" v-model="formSave.serial_number" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="name" label="工程名称" :label-width="formLabelWidth">
                <el-input class="input" clearable placeholder="请输入工程名称" v-model="formSave.name" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="type" label="工程类型" :label-width="formLabelWidth">
                <el-select clearable class="select" v-model="formSave.type" placeholder="请选择工程类型">
                  <el-option label="写字楼" value="写字楼"></el-option>
                  <el-option label="事业单位" value="事业单位"></el-option>
                  <el-option label="园区" value="园区"></el-option>
                  <el-option label="建筑工地" value="建筑工地"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="charge_id" label="区域经理" :label-width="formLabelWidth">
                <el-select clearable class="select" v-model="formSave.charge_id" placeholder="请选择区域经理">
                  <el-option v-for="item in manager" :key="item.id" :label="item.realname" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程经度" :label-width="formLabelWidth">
                <el-input clearable class="input" placeholder="请输入工程经度" v-model="formSave.longitude" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程纬度" :label-width="formLabelWidth">
                <el-input clearable class="input" placeholder="请输入工程纬度" v-model="formSave.latitude" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程地址" :label-width="formLabelWidth">
                <el-cascader v-model="formSave.address1" placeholder="请选择工程地址" class="select" :options="pca"
                  :props="{ label: 'name', value: 'name' }" clearable></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地址" :label-width="formLabelWidth">
                <el-input clearable class="input" placeholder="请输入详细地址" v-model="formSave.address" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="title == '修改工程信息'">
              <el-form-item label="客户名称" :label-width="formLabelWidth">
                <el-select clearable class="select" v-model="formSave.customer_name" placeholder="请选择客户">
                  <el-option v-for="item in customer" :key="item.id" :label="item.realname" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-else>
              <el-form-item label="客户名称" :label-width="formLabelWidth">
                <el-input clearable class="input" placeholder="请输入客户名称" v-model="formSave.customer_name" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户电话" :label-width="formLabelWidth">
                <el-input clearable class="input" placeholder="请输入客户电话" v-model="formSave.customer_telephone" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="toSubmit">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { get, del, postJSON } from '@/utils/request'
import moment from 'moment'
import pca from '@/assets/pca.json'
import _ from 'lodash';
export default {
  data() {
    return {
      pca,
      form: {},
      engData: [],
      params: { page: 1, pageSize: 5 },
      total: 0,
      title: '录入工程信息',
      visible: false,
      formSave: {},
      formLabelWidth: '90px',
      manager: [],
      customer: [],
      rules: {
        serial_number: [{ required: true, message: '请输入工程编号', trigger: "blur" }],
        name: [{ required: true, message: '请输入工程名称', trigger: "blur" }],
        type: [{ required: true, message: '请选择工程类型', trigger: "change" }],
        charge_id: [{ required: true, message: '请选择区域经理', trigger: "change" }]
      }
    }
  },
  methods: {moment,
    toBind(row) {
      this.$router.push({ path: '/am/engineer/Details?id', query: row })
    },
    reset() {
      this.$refs['myForm'].resetFields();
    },
    async toSubmit() {
      this.$refs['myForm'].validate(async (valid) => {
        if (valid) {
          let data = _.clone(this.formSave);
          data.address = data.address1?.join(' ') + ' ' + data.address;
          delete data.address1;
          let res = await postJSON('/engineer/saveOrUpdate', data);
          if (res.status == 200) {
            this.$notify({ title: "成功", message: res.message, type: 'success' });
            this.visible = false;
            this.getEngData();
          } else return false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    toEdit(row) {
      this.visible = true;
      this.title = '修改工程信息';
      this.formSave = _.clone(row);
      this.formSave.address1 = this.formSave.address.split(' ').slice(0, 3);
      this.formSave.address = this.formSave.address.split(' ').slice(3).join(' ');
    },
    toAdd() {
      this.visible = true;
      this.title = "录入工程信息";
      this.formSave = {};
    },
    async queryCustomers() {
      let res = await get("/user/pageQuery", { page: 1, pageSize: 1000, role_id: 4 });
      this.customer = res.data.list;
    },
    async queryEngData() {
      let res = await get("/user/pageQuery", { page: 1, pageSize: 1000, role_id: 3 });
      this.manager = res.data.list;
    },
    async toDelete(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(async () => {
        let res = await del('/engineer/deleteById', { id });
        this.$message({ type: 'success', message: '操作成功!' });
        this.params.page = 1;
        this.getEngData();
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消操作' });
      });
    },
    async toFinish(id) {
      this.$confirm('此操作将永久结束该工程, 是否继续?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(async () => {
        let res = await get('/engineer/finish', { id });
        this.$message({ type: 'success', message: '操作成功!' });
        this.getEngData();
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消操作' });
      });
    },
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.getEngData();
    },
    handleCurrentChange(val) {
      this.params.page = val;
      this.getEngData();
    },
    async getEngData() {
      let res = await get('/engineer/pageQuery', this.params);
      this.engData = res.data.list;
      this.total = res.data.total;
    },
    toSearch() {
      this.params.page = 1;
      this.getDevData();
    },
    async getDevData() {
      let temp = { ...this.form, ...this.params };
      let res = await get('/device/pageQuery', temp);
      this.deviceData = res.data.list;
    }
  },
  created() {
    this.getDevData();
    this.getEngData();
    this.queryEngData();
    this.queryCustomers();
  },
  filters: {
    fmtDate(val) {
      return moment(val).format('YYYY-MM-DD:HH:mm:ss');
    }
  }
}
</script>

<style lang="scss" scoped>
// 1. 页面整体背景（浅粉紫）
.page-container {
  background-color: #f9eaf2;
  min-height: 100vh;
  padding: 20px;
}

// 2. 表格容器背景（稍深粉紫，与整体区分）
.table-container {
  background-color: #f0d9e8;
  padding: 15px;
  border-radius: 8px;
  margin: 15px 0;
}

// 3. 表格内部背景（白色，保证文字清晰）
::v-deep .custom-table {
  background-color: #fff;
}

// 4. 抽屉背景（浅粉紫，与页面呼应）
::v-deep .custom-drawer {
  background-color: #f9eaf2;
}

// 原有样式保留
::v-deep .el-link--inner {
  margin-left: 5px;
}

.input {
  width: 280px;
}

.select {
  width: 280px;
}

.demo-drawer__footer {
  border-top: 1px solid #ececec;
  padding-top: 10px;
  position: fixed;
  bottom: 50px;
  width: 50%;
  text-align: center;
}
</style>